package net.qiqb.core.domain;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import net.qiqb.core.domain.annotation.AggregateRoot;
import net.qiqb.core.domain.annotation.AttachedAggregate;
import net.qiqb.core.domain.annotation.BusinessId;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DomainUtil {

    public static String getAggregateName(Class<?> aggregateRootClass) {
        if (ClassUtil.isSimpleValueType(aggregateRootClass) || ClassUtil.isJdkClass(aggregateRootClass)) {
            return null;
        }
        final AggregateRoot annotation = AnnotationUtil.getAnnotation(aggregateRootClass, AggregateRoot.class);
        if (annotation != null) {
            return "".equals(annotation.name()) ? aggregateRootClass.getName() : annotation.name();
        }
        return null;
    }

    public static List<Field> getBusinessIdFields(Class<?> aggregateRootClass) {
        List<Field> businessIdFields = new ArrayList<>();
        if (!ClassUtil.isSimpleValueType(aggregateRootClass) && !ClassUtil.isJdkClass(aggregateRootClass)) {
            final Field[] fields = ReflectUtil.getFields(aggregateRootClass);
            for (Field f : fields) {
                final BusinessId annotation = AnnotationUtil.getAnnotation(f, BusinessId.class);
                if (annotation != null) {
                    businessIdFields.add(f);
                }
            }
        }

        return businessIdFields;
    }

    public static Class<?> getAggregateRootClass(Class<?> attachedAggregateClass) {
        if (ClassUtil.isSimpleValueType(attachedAggregateClass) || ClassUtil.isJdkClass(attachedAggregateClass)) {
            return null;
        }
        final AttachedAggregate annotation = AnnotationUtil.getAnnotation(attachedAggregateClass, AttachedAggregate.class);
        if (annotation != null) {
            return annotation.value();
        }
        return null;
    }

}
